#include <iostream>
#include <string>
#include <cstring>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
using namespace std;
void usage()
{
    cout << "./server.out ip=0 port" << endl;
}

int main(int argc, char *argv[])
{
    if (argc != 2 && argc != 3)
    {
        usage();
        return 1;
    }
    // 1.创建插座 获取fd
    int socket_fd = socket(AF_INET, SOCK_DGRAM /*udp*/, 0);
    if (socket_fd == -1)
    {
        cerr << "socket_error..." << endl;
        return errno;
    }
    cout << "socket_succeed..." << endl;
    // 2.绑定ip 端口号
    uint32_t ip = argc == 2 ? INADDR_ANY : inet_addr(argv[1]);
    cout<<ip<<endl;
    uint16_t port = htons(atoi(argc == 2 ? argv[1] : argv[2]));
    cout<<atoi(argc == 2 ? argv[1] : argv[2])<<endl;
    // i.创建并初始化套接字
    struct sockaddr_in local;
    bzero(&local, sizeof(local));
    // ii.填充协议家族
    local.sin_family = AF_INET;
    // iii.设置ip 和 端口号
    local.sin_addr.s_addr = ip;
    local.sin_port = port;
    // iiii.绑定
    int bind_ret = bind(socket_fd, (const sockaddr *)&local, sizeof(local));
    if (bind_ret == -1)
    {
        cerr << "bind_error" << endl;
        return errno;
    }
    cout << "bind_succeed..." << endl;
    //提供服务
    //服务端一般是不停机持续提供服务的
    char buffer[2048];
    struct sockaddr_in peer;
    socklen_t len = sizeof(peer);
    bzero(&peer, sizeof(peer));
    bzero(buffer, sizeof(buffer));
    cout<<"ip:"<<local.sin_addr.s_addr<<" prot:"<<local.sin_port<<endl;

    while (1)
    {
        recvfrom(socket_fd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&peer, &len);
        cout << "server_recived:" << string(buffer);
        cout.flush();
    }
    cout << "done" << endl;
    return 0;
}